/**
 * 初始化字典详情对话框
 */
var DictInfoDlg = {
    zTreeInstance:null,
    count: $("#itemSize").val(),
    dictInfoData:  {},			//字典
    mutiString: '',		//拼接字符串内容(拼接字典条目)
    itemTemplate: $("#itemTemplate").html(),
    validateFields: {
        code: {
            validators: {
                notEmpty: {
                    message: '编码不能为空'
                }
            }
        },
        name: {
            validators: {
                notEmpty: {
                    message: '分类不能为空'
                }
            }
        },
        itemKey: {
            validators: {
                notEmpty: {
                    message: '值不能为空'
                }
            }
        },
        itemName: {
            validators: {
                notEmpty: {
                    message: '名称不能为空'
                }
            }
        },
        itemWeight: {
            validators: {
                notEmpty: {
                    message: '排序不能为空'
                }
            }
        }
    }
};

/**
 * 清除数据
 */
DictInfoDlg.clearData = function() {
    this.dictInfoData = {};
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
DictInfoDlg.set = function(key, value) {
    this.dictInfoData[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
DictInfoDlg.get = function(key) {
    return $("#" + key).val();
}
/**
 * item获取新的id
 */
DictInfoDlg.newId = function () {
    if(this.count == undefined){
        this.count = 0;
    }
    this.count = this.count + 1;
    return "dictItem" + this.count;
};

/**
 * 关闭此对话框
 */
DictInfoDlg.close = function () {
    parent.layer.close(window.parent.Dict.layerIndex);
};

/**
 * 添加条目
 */
DictInfoDlg.addItem = function () {
    $("#itemsArea").append(this.itemTemplate);
    var itemId = this.newId();
    $("#dictItem").attr("id", itemId);
    Sys.initValidator(itemId, DictInfoDlg.validateFields);
};

/**
 * 删除item
 */
DictInfoDlg.deleteItem = function (event) {
    var obj = Sys.eventParseObject(event);
    obj.parent().parent().parent().remove();
};

/**
 * 清除为空的item Dom
 */
DictInfoDlg.clearNullDom = function(){
    $("[name='dictItem']").each(function(){
        var name = $(this).find("[name='itemName']").val();
        var key = $(this).find("[name='itemKey']").val();
        if(name == '' || key == ''){
            $(this).remove();
        }
    });
};

/**
 * 收集添加字典的数据
 */
DictInfoDlg.collectData = function () {
    this.clearNullDom();
    var mutiString = "";
    $("[name='dictItem']").each(function(){
        var weight = $(this).find("[name='itemWeight']").val();
        var key = $(this).find("[name='itemKey']").val();
        var name = $(this).find("[name='itemName']").val();
        mutiString = mutiString + (key + ":" + name + ":" + weight + ";");
    });
    this.set('id').set('name').set('code').set('weight').set('categoryId').set('description');
    this.mutiString = mutiString;
};

/**
 * 验证数据是否为空
 */
DictInfoDlg.validate = function () {
    $('#dictInfoForm').data("bootstrapValidator").resetForm();
    $('#dictInfoForm').bootstrapValidator('validate');

    var flag = true;
    $("div[name='dictItem']").each(function(){
        $(this).data("bootstrapValidator").resetForm();
        $(this).bootstrapValidator('validate');
        flag = flag?$(this).data('bootstrapValidator').isValid():flag
    });
    flag = flag?$("#dictInfoForm").data('bootstrapValidator').isValid():flag
    return flag;
};

/**
 * 提交添加字典
 */
DictInfoDlg.addSubmit = function () {
    if (!this.validate()) {
        return;
    }
    this.collectData();
    //提交信息
    var ajax = new $ax(Sys.backendPath + "/dict/add", function (data) {
        Sys.success("添加成功!");
        window.parent.Dict.table.refresh();
        DictInfoDlg.close();
    }, function (data) {
        Sys.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.dictInfoData);
    ajax.set('dictValues',this.mutiString);
    ajax.start();
};

/**
 * 提交修改
 */
DictInfoDlg.editSubmit = function () {
    if (!this.validate()) {
        return;
    }
    this.collectData();
    var ajax = new $ax(Sys.backendPath + "/dict/update", function (data) {
        Sys.success("修改成功!");
        window.parent.Dict.table.refresh();
        DictInfoDlg.close();
    }, function (data) {
        Sys.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.dictInfoData);
    ajax.set('dictValues',this.mutiString);
    ajax.start();
};
/**
 * 点击部门ztree列表的选项时
 *
 * @param e
 * @param treeId
 * @param treeNode
 * @returns
 */
DictInfoDlg.onClickCategory = function(e, treeId, treeNode) {
    $("#categoryName").attr("value", DictInfoDlg.zTreeInstance.getSelectedVal());
    $("#categoryId").attr("value", treeNode.id);
}

/**
 * 显示部门选择的树
 *
 * @returns
 */
DictInfoDlg.showCategorySelectTree = function() {
    Sys.showInputTree("categoryName", "pTreeDiv", 15, 28);
}

$(function() {
    Sys.initValidator("dictInfoForm", DictInfoDlg.validateFields);
    $("[name='dictItem']").each(function(i){
        Sys.initValidator("dictItem"+(i+1), DictInfoDlg.validateFields);
    });
    var ztree = new $ZTree("pTree", Sys.backendPath + "/dictcategory/tree");
    ztree.bindOnClick(DictInfoDlg.onClickCategory);
    ztree.init();
    DictInfoDlg.zTreeInstance = ztree;
});